package servlets;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Connectivity.ConnectionManager;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Servlet implementation class CallPerformedServlet
 */
public class CallPerformedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CallPerformedServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		DocumentException ex = null;
		
		ByteArrayOutputStream baosPDF = null;
		
		try
		{
			baosPDF = generatePDFDocumentBytes(request, this.getServletContext());
			
			String call_performed_id =request.getParameter("call_performed_id");
			StringBuffer sbFilename = new StringBuffer();
			sbFilename.append(call_performed_id+"_");
			sbFilename.append(System.currentTimeMillis());
			sbFilename.append(".pdf");

			////////////////////////////////////////////////////////
			// Note: 
			//
			// It is important to set the HTTP response headers 
			// before writing data to the servlet's OutputStream 
			//
			////////////////////////////////////////////////////////
			//
			//
			// Read the HTTP 1.1 specification for full details
			// about the Cache-Control header
			//
			response.setHeader("Cache-Control", "max-age=30");
			
			response.setContentType("application/pdf");
			
			//
			//
			// The Content-disposition header is explained
			// in RFC 2183
			//
			//    http://www.ietf.org/rfc/rfc2183.txt
			//
			// The Content-disposition value will be in one of 
			// two forms:
			//
			//   1)  inline; filename=foobar.pdf
			//   2)  attachment; filename=foobar.pdf
			//
			// In this servlet, we use "inline"
			//
			StringBuffer sbContentDispValue = new StringBuffer();
			sbContentDispValue.append("inline");
			sbContentDispValue.append("; filename=");
			sbContentDispValue.append(sbFilename);
							
			response.setHeader(
				"Content-disposition",
				sbContentDispValue.toString());

			response.setContentLength(baosPDF.size());

			ServletOutputStream sos;

			sos = response.getOutputStream();
			
			baosPDF.writeTo(sos);
			
			sos.flush();
		}
		catch (Exception dex)
		{
			response.setContentType("text/html");
			PrintWriter writer = response.getWriter();
			writer.println(
					this.getClass().getName() 
					+ " caught an exception: " 
					+ dex.getClass().getName()
					+ "<br>");
			writer.println("<pre>");
			dex.printStackTrace(writer);
			writer.println("</pre>");
		}
		finally
		{
			if (baosPDF != null)
			{
				baosPDF.reset();
			}
		}
		 
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected ByteArrayOutputStream generatePDFDocumentBytes(
			final HttpServletRequest req,
			final ServletContext ctx)
			throws DocumentException, MalformedURLException, IOException, SQLException
			
		{	
		    Document doc = new Document(PageSize.A4, 12f, 12f, 12f, 12f);

		    Font bold = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);
		    Font underline = FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.UNDERLINE);
		    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 8);

			ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
			PdfWriter docWriter = null;

			try
			{
				docWriter = PdfWriter.getInstance(doc, baosPDF);
				
				doc.addAuthor("Genius Infotech");
				doc.addCreationDate();
				doc.addProducer();
				doc.addCreator(this.getClass().getName());
				doc.addTitle("Call Performed report");			

				doc.open();
				
				
				String path1 = "/container/images/";
				String basePath1 = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path1+"/";
				 
				
				Connection con1=ConnectionManager.getConnection();
				  
				   int call_performed_id=0;
				   String address="-",phone_no="-";
				   String complaint_id="",issue_closed_date="",issue_closed_time="",customer_name="",call_date="",action_taken="",nature_fault="",call_time="",call_type="",item_details="",emp_name="",mtaken="",mgiven="",pfp="",remark="";
				  if(req.getParameter("call_performed_id")!=(""))
				  {call_performed_id=Integer.parseInt(""+(req.getParameter("call_performed_id")));}
				  if(call_performed_id>0)
				  {
					  CallableStatement cstmt = null;
				  
						ResultSet calldisplayrs = null;
				 
						    System.out.println("-----------------------callperformedid="+call_performed_id+"------------------------------------------------------------------------------");
						    
							cstmt = con1.prepareCall("{?=call fun_retrieve_callperformed(?,?)}");
							cstmt.registerOutParameter(1, Types.OTHER);
							cstmt.setInt(2, call_performed_id);
							cstmt.setObject(3, calldisplayrs);
							
							con1.setAutoCommit(false);
							cstmt.execute();
							
							calldisplayrs =(ResultSet) cstmt.getObject(1);	
				 	
				  while(calldisplayrs.next())
				{
				 
				  issue_closed_date=""+calldisplayrs.getString(1);
				  issue_closed_time=calldisplayrs.getString(2);
				  complaint_id=calldisplayrs.getString(3);
				  customer_name=calldisplayrs.getString(4);
				  call_date=calldisplayrs.getString(5);
				  call_time=calldisplayrs.getString(6);
				  call_type=calldisplayrs.getString(7);
				  nature_fault=calldisplayrs.getString(8).toUpperCase().replace("<BR>", " ");
				  item_details=calldisplayrs.getString(9);
				   emp_name=calldisplayrs.getString(10);
				    action_taken=calldisplayrs.getString(11).toUpperCase().replace("<BR>", " ");
				    mtaken=calldisplayrs.getString(12);
				  mgiven=calldisplayrs.getString(13);
				  pfp=calldisplayrs.getString(14);
				  remark=calldisplayrs.getString(15);             
				  address=calldisplayrs.getString(16);             
				  phone_no=calldisplayrs.getString(17);             
				  }
/*
				  Image img2 = Image.getInstance(basePath1+"Companyprint.jpg");
			        img2.setAbsolutePosition(0, 260);
			        doc.add(img2);*/


			        for(int i=0; i<2; i++)
			        {
			        
			        Image companHead = Image.getInstance(basePath1+"Companyprint.jpg");
			        
			        
			        PdfPTable table = new PdfPTable(1);
			        //Logo
			        	table.addCell(companHead);
			        
			        //Heading
			        
			            PdfPCell cell = new PdfPCell(new Phrase("SERVICE CALL REPORT",bold));
			            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			            cell.setFixedHeight(22);
			            table.addCell(cell);
			        
			        //Date time complaintid
			        PdfPTable dtComplaint = new PdfPTable(3);
			        
			        PdfPCell date = new PdfPCell(new Phrase("DATE : "+issue_closed_date, normal));
			        date.setHorizontalAlignment(Element.ALIGN_LEFT);
			        date.setBorder(0);
			        date.setFixedHeight(15);
			        dtComplaint.addCell(date);
			        

			        PdfPCell time = new PdfPCell(new Phrase("TIME : "+issue_closed_time,normal));
			        time.setHorizontalAlignment(Element.ALIGN_LEFT);
			        time.setFixedHeight(15);
			        time.setBorder(0);
			        dtComplaint.addCell(time);
			        

			        PdfPCell complaintId = new PdfPCell(new Phrase("COMPLAINT ID : "+complaint_id,normal));
			        complaintId.setHorizontalAlignment(Element.ALIGN_LEFT);
			        complaintId.setBorder(0);
			        complaintId.setFixedHeight(15);
			        dtComplaint.addCell(complaintId);
			        
			        table.addCell(dtComplaint);
			        
			     //customer name and Address
			    	PdfPTable nameAddress = new PdfPTable(3);
			        
			        PdfPCell name = new PdfPCell(new Phrase("CUSTOMER NAME : "+customer_name.trim(),normal));
			        name.setHorizontalAlignment(Element.ALIGN_LEFT);
			        name.setColspan(2);
			        name.setBorder(0);
			        name.setFixedHeight(15);
			        nameAddress.addCell(name);
			        
			        PdfPCell addr = new PdfPCell(new Phrase("ADDRESS : "+address.trim(),normal));
			        addr.setHorizontalAlignment(Element.ALIGN_LEFT);
			        addr.setColspan(1);
			        addr.setFixedHeight(15);
			        addr.setBorder(0);
			        nameAddress.addCell(addr);
			        
			        table.addCell(nameAddress);
			        
			     //Nature of fault and Contact No
			    	PdfPTable natureContact = new PdfPTable(3);
			        
			        PdfPCell nature = new PdfPCell(new Phrase("NATURE OF FAULT : "+nature_fault,normal));
			        nature.setHorizontalAlignment(Element.ALIGN_LEFT);
			        nature.setColspan(2);
			        nature.setBorder(0);
			        nature.setFixedHeight(20);
			        natureContact.addCell(nature);
			        
			        PdfPCell phone = new PdfPCell(new Phrase("CONTACT NO : "+phone_no.trim(),normal));
			        phone.setHorizontalAlignment(Element.ALIGN_LEFT);
			        phone.setColspan(1);
			        phone.setFixedHeight(20);
			        phone.setBorder(0);
			        natureContact.addCell(phone);
			        
			        table.addCell(natureContact);
			        
			        
			    //callLock date, Calllock time, call type, Item details, Employee Name
			    	PdfPTable calldetailsHead = new PdfPTable(5);
			        
			        PdfPCell lockdateHead = new PdfPCell(new Phrase("CALL LOCK DATE",normal));
			        lockdateHead.setHorizontalAlignment(Element.ALIGN_CENTER);
			        lockdateHead.setColspan(1);
			        lockdateHead.setBorder(0);
			        lockdateHead.setFixedHeight(15);
			        calldetailsHead.addCell(lockdateHead);
			        
			        PdfPCell locktimeHead = new PdfPCell(new Phrase("CALL LOCK TIME",normal));
			        locktimeHead.setHorizontalAlignment(Element.ALIGN_CENTER);
			        locktimeHead.setColspan(1);
			        locktimeHead.setBorder(0);
			        locktimeHead.setFixedHeight(15);
			        calldetailsHead.addCell(locktimeHead);
			        
			        PdfPCell callTypeHead = new PdfPCell(new Phrase("CALL TYPE",normal));
			        callTypeHead.setHorizontalAlignment(Element.ALIGN_CENTER);
			        callTypeHead.setColspan(1);
			        callTypeHead.setBorder(0);
			        callTypeHead.setFixedHeight(15);
			        calldetailsHead.addCell(callTypeHead);
			        
			        PdfPCell itemDetailsHead = new PdfPCell(new Phrase("ITEM DETAILS",normal));
			        itemDetailsHead.setHorizontalAlignment(Element.ALIGN_CENTER);
			        itemDetailsHead.setColspan(1);
			        itemDetailsHead.setBorder(0);
			        itemDetailsHead.setFixedHeight(15);
			        calldetailsHead.addCell(itemDetailsHead);
			        
			        PdfPCell empNameHead = new PdfPCell(new Phrase("EMPLOYEE NAME",normal));
			        empNameHead.setHorizontalAlignment(Element.ALIGN_CENTER);
			        empNameHead.setColspan(1);
			        empNameHead.setBorder(0);
			        empNameHead.setFixedHeight(15);
			        calldetailsHead.addCell(empNameHead);
			        
			        table.addCell(calldetailsHead);

			      //callLock date, Calllock time, call type, Item details, Employee Name values
			      	PdfPTable calldetails = new PdfPTable(5);
			          
			          PdfPCell lockdate = new PdfPCell(new Phrase(call_date,normal));
			          lockdate.setHorizontalAlignment(Element.ALIGN_CENTER);
			          lockdate.setColspan(1);
			          lockdate.setBorder(0);
			          lockdate.setFixedHeight(15);
			          calldetails.addCell(lockdate);
			          
			          PdfPCell locktime = new PdfPCell(new Phrase(call_time,normal));
			          locktime.setHorizontalAlignment(Element.ALIGN_CENTER);
			          locktime.setColspan(1);
			          locktime.setBorder(0);
			          locktime.setFixedHeight(15);
			          calldetails.addCell(locktime);
			          
			          PdfPCell callType = new PdfPCell(new Phrase(call_type,normal));
			          callType.setHorizontalAlignment(Element.ALIGN_CENTER);
			          callType.setColspan(1);
			          callType.setBorder(0);
			          callType.setFixedHeight(15);
			          calldetails.addCell(callType);
			          
			          PdfPCell itemDetails = new PdfPCell(new Phrase(item_details.trim(),normal));
			          itemDetails.setHorizontalAlignment(Element.ALIGN_CENTER);
			          itemDetails.setColspan(1);
			          itemDetails.setBorder(0);
			          itemDetails.setFixedHeight(15);
			          calldetails.addCell(itemDetails);
			          
			          PdfPCell empName = new PdfPCell(new Phrase(emp_name.trim().toUpperCase(),normal));
			          empName.setHorizontalAlignment(Element.ALIGN_CENTER);
			          empName.setColspan(1);
			          empName.setBorder(0);
			          empName.setFixedHeight(15);
			          calldetails.addCell(empName);
			          
			          table.addCell(calldetails);

			       //action taken
			         	PdfPTable actionTakenTable = new PdfPTable(15);
			              
			              PdfPCell actiontakenLabel = new PdfPCell(new Phrase("ACTION TAKEN :",normal));
			              actiontakenLabel.setHorizontalAlignment(Element.ALIGN_LEFT);
			              actiontakenLabel.setColspan(2);
			              actiontakenLabel.setBorder(0);
			              actiontakenLabel.setFixedHeight(30);
			              actionTakenTable.addCell(actiontakenLabel);

			              PdfPCell actiontaken = new PdfPCell(new Phrase(action_taken.trim().toUpperCase(),normal));
			              actiontaken.setHorizontalAlignment(Element.ALIGN_LEFT);
			              actiontaken.setColspan(13);
			              actiontaken.setBorder(0);
			              actiontaken.setFixedHeight(30);
			              actionTakenTable.addCell(actiontaken);
			          table.addCell(actionTakenTable);

			       //material taken, material given, pending for parts
			       	PdfPTable mtmgppTable = new PdfPTable(3);
			            
			            PdfPCell mTakenLabel = new PdfPCell(new Phrase("MATERIAL TAKEN",normal));
			            mTakenLabel.setHorizontalAlignment(Element.ALIGN_CENTER);
			            mTakenLabel.setColspan(1);
			            mTakenLabel.setBorder(0);
			            mTakenLabel.setFixedHeight(15);
			            mtmgppTable.addCell(mTakenLabel);

			            PdfPCell mgivenLabel = new PdfPCell(new Phrase("MATERIAL GIVEN",normal));
			            mgivenLabel.setHorizontalAlignment(Element.ALIGN_CENTER);
			            mgivenLabel.setColspan(1);
			            mgivenLabel.setBorder(0);
			            mgivenLabel.setFixedHeight(15);
			            mtmgppTable.addCell(mgivenLabel);
			        
			            PdfPCell ppLabel = new PdfPCell(new Phrase("PENDING FOR PARTS",normal));
			            ppLabel.setHorizontalAlignment(Element.ALIGN_CENTER);
			            ppLabel.setColspan(1);
			            ppLabel.setBorder(0);
			            ppLabel.setFixedHeight(15);
			            mtmgppTable.addCell(ppLabel);
			        
			            table.addCell(mtmgppTable);
			            //material taken, material given, pending for parts
			           	PdfPTable mtmgppTableVal = new PdfPTable(3);
			                
			                PdfPCell mTaken = new PdfPCell(new Phrase(mtaken.trim(),normal));
			                mTaken.setHorizontalAlignment(Element.ALIGN_CENTER);
			                mTaken.setColspan(1);
			                mTaken.setBorder(0);
			                mTaken.setFixedHeight(20);
			                mtmgppTableVal.addCell(mTaken);

			                PdfPCell mgivenval = new PdfPCell(new Phrase(mgiven.trim(),normal));
			                mgivenval.setHorizontalAlignment(Element.ALIGN_CENTER);
			                mgivenval.setColspan(1);
			                mgivenval.setBorder(0);
			                mgivenval.setFixedHeight(20);
			                mtmgppTableVal.addCell(mgivenval);
			            
			                PdfPCell pp = new PdfPCell(new Phrase(pfp,normal));
			                pp.setHorizontalAlignment(Element.ALIGN_CENTER);
			                pp.setColspan(1);
			                pp.setBorder(0);
			                pp.setFixedHeight(20);
			                mtmgppTableVal.addCell(pp);
			            
			                table.addCell(mtmgppTableVal);
			        
			         //Remark
			         	PdfPTable remarkTable = new PdfPTable(10);
			              
			              PdfPCell remarkLabel = new PdfPCell(new Phrase("REMARK : ",normal));
			              remarkLabel.setHorizontalAlignment(Element.ALIGN_LEFT);
			              remarkLabel.setColspan(1);
			              remarkLabel.setBorder(0);
			              remarkLabel.setFixedHeight(20);
			              remarkTable.addCell(remarkLabel);

			              PdfPCell remarks = new PdfPCell(new Phrase(remark.trim().toUpperCase(),normal));
			              remarks.setHorizontalAlignment(Element.ALIGN_LEFT);
			              remarks.setColspan(9);
			              remarks.setBorder(0);
			              remarks.setFixedHeight(20);
			              remarkTable.addCell(remarks);
			              
			              
			          table.addCell(remarkTable);
			                
			       
			        
			        //Signatures Employee Signature , Customer's signature &   stamp
			       	PdfPTable signatureLbl = new PdfPTable(2);
			            
			            PdfPCell empSign = new PdfPCell(new Phrase("EMPLOYEE SIGNATURE",normal));
			            empSign.setHorizontalAlignment(Element.ALIGN_CENTER);
			            empSign.setVerticalAlignment(Element.ALIGN_BOTTOM);	
			            empSign.setColspan(1);
			            empSign.setBorder(0);
			            empSign.setFixedHeight(60);

			            signatureLbl.addCell(empSign);

			            PdfPCell cusSign = new PdfPCell(new Phrase("CUSTOMER'S SIGNATURE & STAMP",normal));
			            cusSign.setHorizontalAlignment(Element.ALIGN_CENTER);
			            cusSign.setVerticalAlignment(Element.ALIGN_BOTTOM);	
			            cusSign.setColspan(1);
			            cusSign.setBorder(0);
			            cusSign.setFixedHeight(60);
			            signatureLbl.addCell(cusSign);
			        
			           
			            table.addCell(signatureLbl);
			            
			        
			        table.setWidthPercentage(100);
			        //table.setSpacingBefore(0f);
			        //table.setSpacingAfter(0f);
			        //cell.setColspan(2);
			        
			        
			       
			        
			        doc.add(table);        
			        if(i<1)
			        {
			        	doc.add(new Paragraph("                       "));
			          
			        	 PdfPTable linetbl = new PdfPTable(1);
			            PdfPCell linecell = new PdfPCell(new Phrase("--------------------------------------------------------------------------------------------------",normal));
			            linecell.setHorizontalAlignment(Element.ALIGN_CENTER);	
			            linecell.setColspan(1);
			            linecell.setBorder(0);
			        	linetbl.addCell(linecell);
			    	    doc.add(linetbl);
			       		
			    	    doc.add(new Paragraph("                       "));
			    	      
			        }
			        }
			        doc.close(); 

			        
			        
				  
				  }
				
				/*				doc.add( makeGeneralRequestDetailsElement(req) );

				doc.newPage();
				
				doc.add( makeHTTPHeaderInfoElement(req) );
*/				
				doc.newPage();
				
				//doc.add( makeHTTPParameterInfoElement(req) );
				
				
				
				
				
			}
			catch (DocumentException dex)
			{
				baosPDF.reset();
				throw dex; 
			}
			finally
			{
				if (doc != null)
				{
					doc.close();
				}
				if (docWriter != null)
				{
					docWriter.close();
				}
			}

			if (baosPDF.size() < 1)
			{
				throw new DocumentException(
					"document has "
					+ baosPDF.size()
					+ " bytes");		
			}
			return baosPDF;
		}

	
	/**
	 * 
	 * 
	 * @param req HTTP request object
	 * @return an iText Element object
	 * 
	 */
	protected Element makeHTTPParameterInfoElement(
					final HttpServletRequest req)
	{
		Map mapParameters = null;
		
		mapParameters = new java.util.TreeMap(req.getParameterMap());

		Table tab = null;

		tab = makeTableFromMap(
				"HTTP parameter name",
				"HTTP parameter value",
				mapParameters);
		
		return (Element) tab;
	}
	
	private static Table makeTableFromMap(
			final String firstColumnTitle,
			final String secondColumnTitle,
			final java.util.Map m)
	{
		Table tab = null;

		try
		{
			tab = new Table(2 /* columns */);
		}
		catch (BadElementException ex)
		{
			throw new RuntimeException(ex);
		}
		
		tab.setBorderWidth(1.0f);
		tab.setPadding(5);
		tab.setSpacing(5);

		tab.addCell(new Cell(firstColumnTitle));
		tab.addCell(new Cell(secondColumnTitle));
		
		tab.endHeaders();

		if (m.keySet().size() == 0)
		{
			Cell c = new Cell("none");
			c.setColspan(tab.columns());
			tab.addCell(c);
		}
		else
		{
			Iterator iter = m.keySet().iterator();
			while (iter.hasNext())
			{
				String strName = (String) iter.next();
				Object value = m.get(strName);
				String strValue = null;
				if (value == null)
				{
					strValue = "";
				}
				else if (value instanceof String[])
				{
					String[] aValues = (String[]) value;   
					strValue = aValues[0];
				}
				else
				{
					strValue = value.toString();
				}
				
				tab.addCell(new Cell(strName));
				tab.addCell(new Cell(strValue));
			}
		}
		
		return tab;
	}
	
	
}
